package com.jpscloud.common.syslog;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.jpscloud.common.entity.SysLog;

@Aspect
@Component
@Order(-100)
public class SysLogAopAction {
	
	private final Logger log = LoggerFactory.getLogger(getClass());
	
	//切入点设置到自定义的log注解上
    @Pointcut("@annotation(SysLogAnnotation)")
	private void pointCutMethod() {
	}

	/**
	 * 记录操作日志
	 */
	@After("pointCutMethod()") // 使用上面定义的切入点
	public void recordLog(JoinPoint joinPoint) {
		Long start = System.currentTimeMillis();
		SysLog log = new SysLog();
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest();
//		User user = (User) request.getSession().getAttribute("user");
//		if (user == null) {
//			logger.warn("user 信息为空");
//		} else {
//			log.setUserId(user.getId());
//			log.setOperator(user.getUserName());
//			log.setCustomerId(user.getCustomerId());
//		}
//		// 下面开始获取 ip，targetType，remark，action
//		try {
//			Map<String, String> map = getLogMark(joinPoint);
//			log.setAction(map.get(LoggerUtil.LOG_ACTION));
//			log.setTargetType(map.get(LoggerUtil.LOG_TARGET_TYPE));
//			log.setRemark(map.get(LoggerUtil.LOG_REMARK));
//			log.setIp(LoggerUtil.getCliectIp(request));
//			logMapper.insert(log);
//		} catch (ClassNotFoundException c) {
//			logger.error(c.getMessage());
//		} catch (Exception e) {
//			logger.error("插入日志异常", e.getMessage());
//		}
//		Long end = System.currentTimeMillis();
//		logger.info("记录日志消耗时间:" + (end - start) / 1000);
	}

	private Map<String, String> getLogMark(JoinPoint joinPoint) throws ClassNotFoundException {
		Map<String, String> map = new HashMap<>();
//		String methodName = joinPoint.getSignature().getName();
//		String targetName = joinPoint.getTarget().getClass().getName();
//		Class targetClass = Class.forName(targetName);
//		Method[] methods = targetClass.getMethods();
//		for (Method method : methods) {
//			if (method.getName().equals(methodName)) {
//				LogAnnotation logAnnotation = method.getAnnotation(LogAnnotation.class);
//				map.put(LoggerUtil.LOG_TARGET_TYPE, logAnnotation.targetType());
//				map.put(LoggerUtil.LOG_ACTION, logAnnotation.action());
//				map.put(LoggerUtil.LOG_REMARK, logAnnotation.remark());
//			}
//		}
		return map;
	}
}
